package org.hawk.gwt.ppc.parser.impl;

import java.io.InputStream;

import org.hawk.gwt.ppc.parser.CompilationUnitDescriptor;
import org.hawk.gwt.ppc.parser.JavaParser;
import org.hawk.gwt.ppc.utils.Name;
import org.hawk.gwt.ppc.utils.PreprocessorException;

import junit.framework.TestCase;

public class CompilationUnitDescriptorTestCase extends TestCase {

	public void testPackage() throws PreprocessorException {
		CompilationUnitDescriptor unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.CompilationUnitMock1");
		assertNotNull(unit);
		assertNotNull(unit.getPackage());
		assertEquals("org.hawk.gwt.ppc.parser.impl.mock", unit.getPackage().getPackageName());
	}

	public void testImports() throws PreprocessorException {
		CompilationUnitDescriptor unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.CompilationUnitMock1");
		assertNotNull(unit);
		assertNotNull(unit.getImports());

		assertEquals(3, unit.getImports().resolveClass("String").size());
		assertEquals("org.hawk.gwt.ppc.parser.impl.mock.String", unit.getImports().resolveClass("String").get(0));
		assertEquals("java.lang.String", unit.getImports().resolveClass("String").get(1));
		assertEquals("String", unit.getImports().resolveClass("String").get(2));
		
		unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.CompilationUnitMock2");
		assertNotNull(unit);
		assertNotNull(unit.getImports());

		assertEquals(4, unit.getImports().resolveClass("String").size());
		assertEquals("org.hawk.gwt.ppc.parser.impl.mock.String", unit.getImports().resolveClass("String").get(0));
		assertEquals("java.io.String", unit.getImports().resolveClass("String").get(1));
		assertEquals("java.lang.String", unit.getImports().resolveClass("String").get(2));
		assertEquals("String", unit.getImports().resolveClass("String").get(3));
		
		assertEquals(1, unit.getImports().resolveClass("ObjectInput").size());
		assertEquals("java.io.ObjectInput", unit.getImports().resolveClass("ObjectInput").get(0));
	}
	
	public void testClasses() throws PreprocessorException {
		CompilationUnitDescriptor unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.CompilationUnitMock1");
		assertNotNull(unit);
		assertTrue(unit.getTopClasses().isEmpty());
		
		unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.CompilationUnitMock2");
		assertEquals(3, unit.getTopClasses().size());
	}
	
	public void testAnnotatedPackage() throws PreprocessorException {
		CompilationUnitDescriptor unit = getCU("org.hawk.gwt.ppc.parser.impl.mock.package-info");
		assertNotNull(unit);
		assertEquals("org.hawk.gwt.ppc.parser.impl.mock", unit.getPackage().getPackageName());
		
	}
	
	private CompilationUnitDescriptor getCU(String name) throws PreprocessorException {
		InputStream cu = getClass().getClassLoader().getResourceAsStream(Name.javaToFs(name));
		try {
			JavaParser parser = JavaParser.create(cu);
			return parser.parse();
		} finally {
			try {
				cu.close();
			} catch(Exception ex) {
			}
		}
	}
}
